package secret.hehe.com.secret.Activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.Util.Util;

import static secret.hehe.com.secret.Util.Util.changeImg;
import static secret.hehe.com.secret.Util.Util.doSelect;
import static secret.hehe.com.secret.Util.Util.doUpdate;
import static secret.hehe.com.secret.Util.Util.makeRoundImage;



public class RegisterActivity extends AppCompatActivity {
    private String jsonString;
    private int icon = 0;
    private String userId;
    private EditText id;
    private EditText pwd;
    private EditText pwd_repeat;
    private ImageView imageView;
    private int canClick=1;
    private int isUpdate=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        try {
            //修改信息执行，注册不执行
            Intent intent = getIntent();
            isUpdate =(int) intent.getSerializableExtra("isUpdate");
            userId = (String) intent.getSerializableExtra("userId");
            icon = (int) intent.getSerializableExtra("icon");
        }catch (Exception e){
            e.printStackTrace();
        }
        //防止杀死变量
        if (savedInstanceState != null) {
            try {
                isUpdate =savedInstanceState.getInt("isUpdate");
                userId = savedInstanceState.getString("userId");
                icon = savedInstanceState.getInt("icon");
                canClick = savedInstanceState.getInt("canClick");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        id=(EditText)findViewById(R.id.register_user_text);
        pwd=(EditText)findViewById(R.id.register_pwd_text);
        pwd_repeat=(EditText)findViewById(R.id.register_pwd_repeat_text);
        Button register_button = (Button) findViewById(R.id.register_button);
        Button update_button = (Button) findViewById(R.id.update_button);

        if(isUpdate==0){
            //注册时隐藏修改
            this.setTitle("注册");
            update_button.setVisibility(View.INVISIBLE);
            register_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(canClick==1) {
                        canClick=0;
                        if(checkText()){
                            String params = "id=" + URLEncoder.encode(id.getText().toString()) + "&pwd=" +
                                    URLEncoder.encode(pwd.getText().toString())+"&icon="+icon;
                            Util util = new Util();
                            Util.postThread registerThread = util.new postThread("/user/reg",getApplicationContext(),params,handler,1);
                            registerThread.start();
                        }else{
                            canClick=1;
                        }
                    }else{
                        return;
                    }
                }
            });
        }else{
            //修改信息时修改某些文字
            this.setTitle("修改信息");
            register_button.setVisibility(View.INVISIBLE);
            TextView oldPWD = (TextView)findViewById(R.id.register_user_name);
            oldPWD.setText("旧\n密码");
            TextView newPWD = (TextView)findViewById(R.id.register_pwd_name);
            newPWD.setText("新\n密码");
            id.setSingleLine();
            id.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
            //修改信息按钮
            update_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(canClick==1) {
                        canClick=0;
                        new AlertDialog.Builder(RegisterActivity.this).setTitle("提示")
                                .setMessage("修改密码将需要重新登录")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if(checkText()){
                                            String params = "id=" + userId +"&pwd=" + URLEncoder.encode(id.getText().toString())
                                                        + "&newpwd=" + URLEncoder.encode(pwd.getText().toString())+"&icon="+icon;
                                            Util util = new Util();
                                            Util.postThread updateThread = util.new postThread("/user/updateUser",getApplicationContext(),params,handler,2);
                                            updateThread.start();
                                        }else{
                                            canClick=1;
                                        }
                                    }
                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                canClick=1;
                                return;
                            }
                        }).setCancelable(false).show();

                    }else{
                        return;
                    }
                }
            });
        }

        //更换头像
        imageView = (ImageView) findViewById(R.id.registerHead);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RegisterActivity.this,HeadEditActivity.class);
                intent.putExtra("icon", icon);
                startActivityForResult(intent,1001);
            }
        });
        changeImg(icon,imageView,getApplicationContext());


        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //刷新信息
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == 1000) {
            //获取修改头像
            icon =(int) data.getSerializableExtra("icon");
            changeImg(icon,imageView,getApplicationContext());
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存变量
        super.onSaveInstanceState(outState);
        outState.putString("userId", userId);
        outState.putInt("icon", icon);
        outState.putInt("canClick", canClick);
        outState.putInt("isUpdate", isUpdate);
    }

    private boolean checkText(){
        if(isUpdate==0){
            //注册时
            if(id.getText().toString().replace(" ","").equals("")){
                Toast.makeText(RegisterActivity.this, "请输入正确账号", Toast.LENGTH_SHORT).show();
                return false;
            }
        }else{
            //修改时

//            if(id.getText().toString().replace(" ","").equals("")||pwd.getText().toString().replace(" ","").equals("")
//                    ||pwd_repeat.getText().toString().replace(" ","").equals("")){
//                //只修改头像
//                return true;
//            }
            if(id.getText().toString().length()==0){
                Toast.makeText(getApplicationContext(), "请输入旧密码", Toast.LENGTH_SHORT).show();
                return false;
            }
            if(pwd.getText().toString().length()==0){
                Toast.makeText(getApplicationContext(), "请输入新密码", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        //检查文本框
        if(pwd.getText().toString().length()<6||pwd.getText().toString().length()>12){
            Toast.makeText(getApplicationContext(), "密码请设置6-12位", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(pwd_repeat.getText().toString().length()==0){
            Toast.makeText(getApplicationContext(), "请重复密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!(pwd.getText().toString().equals(pwd_repeat.getText().toString()))){
            Toast.makeText(RegisterActivity.this, "重复输入的密码不正确", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    Handler handler = new Handler() {
        //相应接受数据
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){//注册成功
                        canClick=1;
                        new AlertDialog.Builder(RegisterActivity.this).setTitle("提示")//设置对话框标题
                                .setMessage("请记住您的账号为"+id.getText().toString())//设置显示的内容
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                        finish();
                                    }
                                }).show();
                    }else{
                        canClick=1;
                        Toast.makeText(RegisterActivity.this, "该账户已存在", Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 2) {
                canClick=1;
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    String message = jsonObject.getString("message");
                    if(code==200){//修改成功
                        Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
                        JSONArray jsonArray = doSelect("user","id='"+userId+"'",getApplicationContext());
                        JSONObject newJsonObject = (JSONObject) jsonArray.opt(0);
                        newJsonObject.put("icon",icon);
                        JSONArray newJsonArray = new JSONArray();
                        newJsonArray.put(newJsonObject);
                        doUpdate("user",newJsonArray,getApplicationContext());
                        Intent intent = new Intent();
                        intent.putExtra("icon",icon);
                        if(pwd.getText().toString().equals(id.getText().toString())){
                            //没修改密码
                            setResult(1003,intent);
                        }else{
                            //修改密码需要重新登录
                            setResult(1004,intent);
                        }
                        finish();
                    }else{
                        Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 0) {
                canClick=1;
                Toast.makeText(RegisterActivity.this, "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
            }
        }
    };


}
